<template>
	<div class="clockin-rule">
		<div style=" width: 100%;display: flex;justify-content: space-between;">
			<div>
				<el-button type="primary" @click="openHolidays">设置节假日</el-button>
			</div>
			<div style="display: flex;">
				<div style="margin-right: 10px;">
					<el-select v-model="fromData.ruleType" @change="getClockinRuleList">
						<el-option :value="1" label="部门"></el-option>
						<el-option :value="0" label="个人"></el-option>
					</el-select>
				</div>
				<!-- 条件查询 -->
				<el-input v-model="fromData.employeeId" v-show="fromData.ruleType === 0"
					clearable placeholder="按手机号或姓名搜索" @clear="onSubmit"
					@change="onSubmit">
				</el-input>
			</div>
		</div>
		<div class="clockin-rule-table">
			<el-table :data="tableData" v-loading="loading" border stripe 
				style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" fixed="left" width="80">
				</el-table-column>
				<el-table-column prop="nickName" label="姓名" fit
					v-if="fromData.ruleType === 0">
				</el-table-column>
				<el-table-column prop="name" label="部门" fit
					v-if="fromData.ruleType === 1" >
				</el-table-column>
				<el-table-column prop="forenoonCheckinTime" label="上午签到时间" width="160">
					<template slot-scope="scope">
						<el-time-picker v-model="scope.row.forenoonCheckinTime" readonly 
							placeholder="未设置规则" style="width: 135px;">
						</el-time-picker>
					</template>
				</el-table-column>
				<el-table-column prop="forenoonCheckoutTime" label="上午签退时间" width="160">
					<template slot-scope="scope">
						<el-time-picker v-model="scope.row.forenoonCheckoutTime" readonly 
							placeholder="未设置规则" style="width: 135px;">
						</el-time-picker>
					</template>
				</el-table-column>
				<el-table-column prop="afternoonCheckinTime" label="下午签到时间" width="160">
					<template slot-scope="scope">
						<el-time-picker v-model="scope.row.afternoonCheckinTime" readonly 
							placeholder="未设置规则" style="width: 135px;">
						</el-time-picker>
					</template>
				</el-table-column>
				<el-table-column prop="afternoonCheckoutTime" label="下午签退时间" width="160">
					<template slot-scope="scope">
						<el-time-picker v-model="scope.row.afternoonCheckoutTime" readonly 
							placeholder="未设置规则" style="width: 135px;">
						</el-time-picker>
					</template>
				</el-table-column>
				<el-table-column prop="clockinTimePeriod" label="打卡时间段" fit>
					<template slot-scope="scope">
						<div v-if="scope.row.clockinTimePeriod != null">
							{{scope.row.clockinTimePeriod}}
						</div>
						<div v-else>
							未设置规则
						</div>
					</template>
				</el-table-column>
				<el-table-column label="打卡范围" fit>
					<template slot-scope="scope">
						<el-button v-if="scope.row.coordinate != null" type="text" size="mini"
							@click="viewPosition(scope.row.coordinate)">
							点击查看
						</el-button>
						<div v-else>
							未设置规则
						</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120" fixed="right">
					<template slot-scope="scope">
						<div style="display: flex">
							<el-button @click="details(scope.row)" type="text" size="mini">
								编辑
							</el-button>
							<el-divider direction="vertical"></el-divider>
							<el-button @click="reset(scope.row)" type="text" size="mini">
								重置
							</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="fromData.currentPage" :page-sizes="[20, 50, 100]" :page-size="fromData.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>

		<!-- 展示地图 -->
		<el-dialog style="margin-top:0" :visible.sync="mapShow" width="75%" title="打卡范围" @close="mapCloseDialog">
			<MapPolygon style="height: 500px;" :coordinate="clockinPosition"></MapPolygon>
		</el-dialog>

		<!-- 假期表格 -->
		<el-dialog style="margin-top:0" :visible.sync="holidaysShow" width="75%" title="节假日"
			@close="holidaysCloseDialog">
			<div style="height: 450px;">
				<el-form inline ref="holidaysForm">
					<el-form-item label="新增假期">
						<el-date-picker type="dates" v-model="holidays.dates" :picker-options="holidaysOptions"
							placeholder="选择日期">
						</el-date-picker>
						<el-select v-model="holidays.yearValue" placeholder="选择年" @change="changeYear"
							style="width: 100px;">
							<el-option v-for="item in yearList" :key="item" :label="item" :value="item">
							</el-option>
						</el-select>
						<el-select v-model="holidaysType" clearable placeholder="选择类型" @change="changeType"
							style="width: 120px;">
							<el-option label="双休" :value="0"></el-option>
							<el-option label="单休" :value="1"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="addHolidays">添加</el-button>
					</el-form-item>
				</el-form>
				<el-table :data="holidaysTableData" v-loading="holidaysLoading" border stripe style="width: 100%;"
					max-height="400">
					<el-table-column prop="yearValue" label="年" width="200"></el-table-column>
					<el-table-column prop="dates" label="日期" fit>
						<template slot-scope="scope">
							<el-date-picker type="dates" v-model="scope.row.dates"
								:picker-options="{disabledDate: (time) => 
								disabledDate(time, scope.row)}" :clearable="scope.row.edit"
								@change="changeDates(scope.row)" placeholder="选择日期"
								style="width: 100%;">
							</el-date-picker>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="150" fixed="right">
						<template slot-scope="scope">
							<div style="display: flex">
								<el-button @click="editHolidays(scope.row)" type="text" size="mini">
									编辑
								</el-button>
								<el-divider direction="vertical"></el-divider>
								<el-button @click="deleteHolidays(scope.row)" type="text" size="mini">
									删除
								</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import MapPolygon from "../../components/AMap/MapPolygon.vue"
	import employeeAttendanceApi from "../../api/employeeAttendance.js"
	import departmentApi from "../../api/departmentManage.js";
	export default {
		components: {
			MapPolygon
		},
		data() {
			return {
				holidaysTableData: [],
				holidaysShow: false,
				mapShow: false,
				total: 0,
				tableData: [],
				loading: false,
				holidaysLoading: false,
				fromData: {
					currentPage: 1,
					pageSize: 50,
					employeeId: null,
					ruleType: 1
				},
				clockinRule: {
					id: null,
				},
				pickerOptions: {
					disabledDate(time) {
						return true;
					}
				},
				clockinPosition: [],
				holidays: {
					yearValue: null,
					dates: []
				},
				yearList: [],
				dateList: [],
				holidaysType: null,
				holidaysOptions: {
					disabledDate: (time) => {
						const year = time.getFullYear();
						return year !== this.holidays.yearValue;
					}
				},
				holidaysEdit: false,


			}
		},
		created() {
			this.initYear();
			this.getClockinRuleList();
		},
		methods: {
			// 条件查询提交
			onSubmit() {
				this.fromData.currentPage = 1
				this.fromData.pageSize = 50
				this.getClockinRuleList()
			},

			// pageSize变化
			handleSizeChange(pageSize) {
				this.fromData.pageSize = pageSize
				this.getClockinRuleList()
			},
			// 页码变化
			handleCurrentChange(curPage) {
				this.fromData.currentPage = curPage
				this.getClockinRuleList()
			},
			// 获取打卡规则列表
			getClockinRuleList() {
				this.loading = true;
				employeeAttendanceApi.getClockinRuleList(this.fromData).then(res => {
					if (res.code === 200) {
						//console.log("获取的数据>", res.data)
						this.tableData = res.data.clockinRuleVoList.map((item,index) =>{
							item.i = (this.fromData.currentPage - 1) * this.fromData.pageSize + index + 1;
							return item;
						})
						this.total = res.data.total
						this.loading = false
					}
				})
			},
			// 查看打卡范围
			viewPosition(clockinPosition) {
				this.clockinPosition = clockinPosition
				//console.log("打卡范围==>",this.clockinPosition)
				this.mapShow = true
			},
			// 关闭地图
			mapCloseDialog() {
				this.clockinPosition = new Array();
				this.mapShow = false;
			},
			reset(item) {
				// 判断
				//console.log("item=>",item)
				if (item.forenoonCheckinTime === null){
					this.$message.warning("无需重置")
					return;
				}
				
				this.$confirm('确定要重置吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let data = {
						id: item.id
					}
					employeeAttendanceApi.resetClockinRule(data).then(res => {
						if (res.code === 200) {
							this.$message.success("重置成功")
							this.getClockinRuleList();
						}
					})
				}).catch(() => {
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消删除'
					// });
				});

			},

			// 编辑
			details(item) {
				//console.log("item=>",item)
				localStorage.setItem("clockinRule", JSON.stringify(item))
				this.$router.push({
					path: "/employeeAttendance/editClockinRule"
				})
			},
			// 打开假期弹窗
			openHolidays() {
				this.getHolidays();
				this.holidaysShow = true;
			},
			// 关闭假期弹窗
			holidaysCloseDialog() {
				this.holidays.dates = new Array();
				this.holidaysShow = false;
			},
			// 获取假期
			getHolidays() {
				this.holidaysLoading = true;
				employeeAttendanceApi.getHolidays().then(res => {
					if (res.code === 200) {
						//console.log("假期数据=>", res.data)
						res.data.forEach(item => {
							let dateList = new Array
							item.dates.forEach(date => {
								dateList.push(new Date(date))
							})
							item.dates = dateList;
							this.$set(item, "edit", false)
							// item.edit = false;
						});
						this.holidaysTableData = res.data
						this.holidaysLoading = false;
					}
				})
			},
			// 添加假期
			addHolidays() {
				//console.log("提交的日期==>",this.holidays)
				if (this.holidays.dates.length === 0) {
					this.$message.error("请选择日期")
					return;
				}
				employeeAttendanceApi.addHolidays(this.holidays).then(res => {
					if (res.code === 200) {
						this.$message.success("添加成功");
						this.getHolidays();
						this.changeYear();
					}else if(res.code === 409){
						this.$message.error("已有该年份");
					}
				})
			},
			// 假期编辑按钮
			editHolidays(item) {
				//console.log("item==>", item)
				this.$message.warning("点击日期进行编辑")
				item.edit = true
			},
			// 假期删除按钮
			deleteHolidays(item) {
				this.$confirm("确定要删除吗?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const data = {
						id: item.id
					}
					employeeAttendanceApi.deleteHolidays(data).then(res => {
						if (res.code === 200) {
							this.$message.success("删除成功")
							this.getHolidays();
						}
					})
				}).catch(() => {
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消删除'
					// });
				});

			},
			// 日期变化
			changeDates(item) {
				console.log("item==>", item)
				if(item.dates === null || item.dates.length === 0){
					this.$message.error("请选择日期")
					return;
				}
				employeeAttendanceApi.updateHolidays(item).then(res => {
					if (res.code === 200) {
						this.$message.success("修改成功");
					}
				})
				item.edit = false;
			},
			// 初始化年
			initYear() {
				// 获取当前年份
				const currentYear = new Date().getFullYear();
				this.holidays.yearValue = currentYear
				// 生成当前年前3年到当前年后7年的数组
				const yearsArray = [];
				for (let i = currentYear - 3; i <= currentYear + 7; i++) {
					yearsArray.push(i);
				}
				this.yearList = yearsArray;
				//console.log(yearsArray);
			},
			// 年份发生改变清空选择的日期
			changeYear() {
				this.holidays.dates = new Array();
				this.holidaysType = null;
			},
			// 选择假期类型
			changeType(e) {
				//console.log("e=>", e)
				const weekends = new Array();
				const year = this.holidays.yearValue;
				for (let month = 0; month < 12; month++) {
					for (let date = 1; date <= 31; date++) {
						const currentDate = new Date(year, month, date);
						if (e === 0) {
							if (currentDate.getFullYear() === year &&
								(currentDate.getDay() === 0 || currentDate.getDay() === 6)) {
								weekends.push(currentDate);
							}
						} else if (e === 1) {
							if (currentDate.getFullYear() === year && currentDate.getDay() === 0) {
								weekends.push(currentDate);
							}
						}
					}
				}
				this.holidays.dates = weekends;
				//console.log("weekends=>", weekends)
			},
			// 控制日期是否可编辑
			disabledDate(time, item) {
				// console.log("time=>",time)
				// console.log("item=>",item)
				if (item.edit) {
					const year = time.getFullYear();
					return year.toString() === item.yearValue ? false : true;
				} else {
					return true;
				}

			}
		}
	}
</script>

<style>
	.clockin-rule {
		height: 100%;
	}
	
	.clockin-rule-table {
		height: 94%;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}
</style>